<template>
	<view class="online-work-flow-form" style="position: relative; height: 100%;">
		<u-form
			ref="form"
			:model="formData"
			:label-width="(form.labelWidth || 100) + 'px'"
			label-align="left"
			:errorType="['border-bottom', 'message']"
		>
			<online-custom-block v-if="isReady" :widgetList="form.widgetList" />
		</u-form>
		<!-- 弹出子表单 -->
		<u-popup v-if="showSubPage" v-model="showSubPage" mode="left" length="100%" style="background: #F6F6F6;">
			<online-form :formId="subFormId" :rowData="editRowData" @close="onCloseSubForm" :saveData="false" />
		</u-popup>
	</view>
</template>

<script>
	import {
		OnlineFormMixins
	} from './onlineFormMixins.js';
	import { FlowOperationController } from '@/api/flowController.js';
	import { formRuleMixin } from '@/utils/validate.js';

	export default {
		name: 'onlineWorkFlowForm',
		props: {
			formConfig: {
				type: Object,
				required: true
			},
			flowInfo: {
				type: Object
			},
			readOnly: {
				type: Boolean,
				default: false
			}
		},
		mixins: [OnlineFormMixins, formRuleMixin],
		provide() {
			return {
				form: () => {
					return {
						...this.form,
						getDictDataList: this.getDictDataList,
						getWidgetValue: this.getWidgetValue,
						getWidgetVisible: this.getWidgetVisible,
						onValueChange: this.onValueChange,
						onWidgetValueChange: this.onWidgetValueChange,
						getDropdownParams: this.getDropdownParams,
						masterTable: this.masterTable,
						handlerOperation: this.handlerOperation,
						checkOperationVisible: this.checkOperationVisible,
						getPrimaryData: this.getPrimaryData,
						formData: this.formData,
						flowData: this.flowInfo,
						rules: this.rules,
						widgetImplList: this.widgetImplList,
						formAuth: () => {
							return this.formAuth
						}
					}
				}
			}
		},
		data() {
			return {
				isStart: false,
				isUpdateFrom:0,
				isReady: false,
				// 保存草稿后流程taskId
				draftTaskId: undefined,
				// 保存草稿后流程实例ID
				draftProcessInstanceId: undefined
			}
		},
		methods: {
			onCloseSubForm(refresh, data) {
				if (refresh && this.operationCallback) {
					this.operationCallback(data);
				}
				this.showSubPage = false;
			},
			getTableData(widget) {
				return widget.relation ? this.formData[widget.relation.variableName] : [];
			},
			setTableData(widget, dataList) {
				if (widget == null) return;
				if (widget.relation) {
					this.formData[widget.relation.variableName] = dataList;
				}
			},
			initFormData() {
				if (this.flowInfo == null || this.flowInfo.processInstanceId == null) return Promise.resolve();
				return new Promise((resolve, reject) => {
					let params = {
						processInstanceId: this.flowInfo.processInstanceId,
						taskId: this.flowInfo.taskId
					}
					// 判断是展示历史流程的数据还是待办流程的数据
					let httpCall = null;
					if (this.isDraft) {
						// 草稿数据
						httpCall = FlowOperationController.viewOnlineDraftData(this, {
							processDefinitionKey: this.flowInfo.processDefinitionKey,
							processInstanceId: this.flowInfo.processInstanceId
						});
					} else if (this.flowInfo.messageId != null) {
						// 抄送消息
						httpCall = FlowOperationController.viewOnlineCopyBusinessData(this, {
							messageId: this.flowInfo.messageId
						});
					} else {
						// 脱敏设置，审批暂时不支持脱敏
						// params.ignoreMaskFields = this.getIgnoreMaskFields();
						httpCall = (this.flowInfo.taskId != null && this.isRuntime) ?
							FlowOperationController.viewUserTask(this, params) : FlowOperationController.viewHistoricProcessInstance(this, params);
					}
					httpCall.then(res => {
						this.isStart = (res == null);
						// 流程数据
						let masterData = (res || {})[this.masterTable.datasource.variableName] || {};
						// 初始化表单字段
						let relationNameList = new Map();
						let datasourceName;
						this.form.tableMap.forEach(table => {
							if (table.relation) {
								if (table.relation.relationType === 0 || this.isDraft) {
									relationNameList.set(table.relation.variableName, table
										.relation);
								} else {
									relationNameList.set(table.relation.variableName + 'List',
										table.relation);
								}
							} else if (table.relation == null) {
								datasourceName = table.datasource.variableName;
							}
						});
						Object.keys(masterData).forEach(key => {
							let relation = relationNameList.get(key);
							let relationVariableName = (relation || {}).variableName;
							if (relationVariableName == null) {
								// 主表字段
								this.formData[datasourceName][key] = masterData[key];
							} else {
								// 从表字段
								if (relation.relationType === 1 && masterData[key]) {
									// 如果是一对多关联字段，判断表单上使用这个字段的table组件是否支持数据加载数据后脚本
									if (Array.isArray(this.tableWidgetList)) {
										this.tableWidgetList.forEach(tableWidget => {
											if (tableWidget.relation && tableWidget
												.relation.relationId === relation
												.relationId) {
												if (tableWidget.eventInfo && typeof tableWidget.eventInfo['afterLoadTableData'] === 'function') {
													masterData[key] = tableWidget
														.eventInfo['afterLoadTableData'](
															masterData[key]);
												}
											}
										});
									}
								}
								if (masterData[key]) {
									this.formData[relationVariableName] = masterData[key];
								}
							}
						});
						relationNameList = null;
						resolve();
					}).catch(e => {
						reject(e);
					});
				});
			},
			async getFormDataImpl(variableList) {
				let tempObj = {};
				// 获取表单数据
				this.form.tableMap.forEach(table => {
					if (table.relation) {
						if (tempObj.slaveData == null) tempObj.slaveData = {};
						tempObj.slaveData[table.relation.variableName] = this.formData[table.relation
							.variableName];
					} else if (table.relation == null) {
						tempObj.masterData = this.formData[table.datasource.variableName];
					}
				});
				// 获取流程变量
				if (Array.isArray(variableList)) {
					variableList.forEach(variable => {
						if (!variable.builtin) {
							let column = this.form.columnMap.get(variable.bindColumnId);
							let relation = this.form.relationMap.get(variable.bindRelationId);
							if (column != null) {
								if (tempObj.taskVariableData == null) tempObj.taskVariableData = {};
								if (relation == null) {
									tempObj.taskVariableData[variable.variableName] = this.formData[this
										.masterTable.datasource.variableName][column.columnName] || '';
								} else {
									tempObj.taskVariableData[variable.variableName] = this.formData[relation
										.variableName][column.columnName] || '';
								}
							}
						}
					});
				}

				// 执行提交数据前脚本
				if (this.form.eventInfo && typeof this.form.eventInfo[this.OnlineFormEventType.BEFORE_COMMIT_FORM_DATA] === 'function') {
					tempObj = await this.form.eventInfo[this.OnlineFormEventType.BEFORE_COMMIT_FORM_DATA](tempObj);
				}
				if (tempObj == null) throw new Error('提交数据前脚本返回数据为空');
				// 把slaveData里的relationVariableName替换成relationId
				if (tempObj.slaveData) {
					let slaveDataKeyList = Object.keys(tempObj.slaveData);
					if (slaveDataKeyList.length > 0) {
						let relationVariableNameMap = new Map();
						this.form.tableMap.forEach(table => {
							if (table.relation != null) {
								relationVariableNameMap.set(table.relation.variableName, table.relation
									.relationId);
							}
						});
						slaveDataKeyList.forEach(key => {
							let relationId = relationVariableNameMap.get(key);
							if (relationId != null) {
								tempObj.slaveData[relationId] = tempObj.slaveData[key];
							}
							tempObj.slaveData[key] = undefined;
						});
					}
				}

				return tempObj;
			},
			getFormData(isDraft, variableList) {
				// 获取富文本内容
				if (Array.isArray(this.richEditWidgetList)) {
					this.richEditWidgetList.forEach(richWidget => {
						if (richWidget && richWidget.widgetImpl) {
							this.onValueChange(richWidget, richWidget.widgetImpl.getHtml());
						}
					});
				}
				
				return new Promise((resolve, reject) => {
					if (isDraft) {
						this.getFormDataImpl().then(res => {
							resolve(res);
						}).catch(e => {
							reject(e);
						});
					} else {
						this.$refs.form.validate(valid => {
							if (!valid) {
								reject();
								return;
							};
							this.$nextTick(() => {
								this.getFormDataImpl(variableList).then(res => {
									resolve(res);
								}).catch(e => {
									reject(e);
								});
							});
						});
					}
				});
			},
			viewTaskFormKey() {
				if (
					this.flowInfo == null ||
					this.flowInfo.processDefinitionKey == null ||
					this.flowInfo.processDefinitionKey === ''
				) {
					return Promise.resolve();
				}
				let paraams = {
					processDefinitionKey: this.flowInfo.processDefinitionKey,
					processInstanceId: this.flowInfo.processInstanceId,
					taskId: this.flowInfo.taskId
				};
				return new Promise((resolve, reject) => {
					FlowOperationController.viewTaskFormKey(this, paraams)
						.then(res => {
							try {
								console.log(res);
								let temp = JSON.parse(res);
								this.formAuth = temp.formAuth;
								Object.keys(this.formAuth || {}).forEach(key => {
									let formAuthItem = this.formAuth[key];
									Object.keys(formAuthItem).forEach(subKey => {
										let authItem = formAuthItem[subKey];
										if (authItem && authItem != null && authItem !== '') {
											formAuthItem[subKey] = authItem.split(',').map(item => parseInt(item));
										} else {
											formAuthItem[subKey] = [0, 0];
										}
										let disabled = formAuthItem[subKey][0] === 1;
										let hide = formAuthItem[subKey][1] === 1;
										formAuthItem[subKey].disabled = disabled;
										formAuthItem[subKey].hide = hide;
									});
								});
								console.log(this.formAuth);
							} catch (e) {
								console.log(e);
								this.formAuth = null;
							}
							resolve();
						})
						.catch(e => {
							reject(e);
						});
				});
			}
		},
		computed: {
			form() {
				this.isUpdateFrom++
				return this.buildFormConfig(this.formConfig);
			},
			isDraft() {
				return this.flowInfo ? (this.flowInfo.isDraft || this.flowInfo.isDraft === 'true') : false
			},
			rootWidget() {
				return {
					childWidgetList: this.form.widgetList
				}
			}
		},
		watch: {
			isUpdateFrom: {
				handler() {
					this.isReady = false;
					this.viewTaskFormKey().then(() => {
						this.initPage();
						this.initFormWidgetList();
						this.initWidgetRule(this.form);
						if (this.form.eventInfo && typeof this.form.eventInfo[this.OnlineFormEventType.AFTER_CREATE_FORM] === 'function') {
							this.form.eventInfo[this.OnlineFormEventType.AFTER_CREATE_FORM]();
						}
						// this.initWidgetRule();
						this.initFormData().then(() => {
							if (this.form.eventInfo && typeof this.form.eventInfo[this.OnlineFormEventType.AFTER_LOAD_FORM_DATA] === 'function') {
								this.form.eventInfo[this.OnlineFormEventType.AFTER_LOAD_FORM_DATA]();
							}
							this.initWidgetLinkage();
						}).catch(e => {});
						this.isReady = true;
					});
				},
				immediate: true
			}
		},
		created() {
			
		}
	}
</script>

<style>

</style>
